from sqlalchemy import Column
from sqlalchemy.dialects.mysql import INTEGER, VARCHAR, BOOLEAN
from sqlalchemy.dialects.mysql.types import TINYINT

from utils.db import Base, NotNullColumn, model_to_dict, db, models_to_list


class Task(Base):
    __tablename__ = 'tb_task'
    id = Column(INTEGER, primary_key=True)
    task_id = NotNullColumn(VARCHAR(64))                   # task_id
    task_name = NotNullColumn(VARCHAR(64))                 # 调用的task
    status = NotNullColumn(TINYINT(1), default=0)          # 任务执行状态 0 初始 1 执行成功
    is_compensated = NotNullColumn(TINYINT(1), default=0)  # 任务是否被补偿执行 0 否 1 是


    @model_to_dict
    def add(self, **kw):
        return db.add(Task(**kw))


    @model_to_dict
    def get(self, task_id):
        r = db.master.query(Task).filter_by(task_id=task_id).scalar()
        return r


    def task_down(self, task_id):
        db.master.query(Task).filter_by(task_id=task_id).update(status=1)
        db.commit()


    def is_done(self, task_id):
        r = db.master.query(Task).filter_by(task_id=task_id, status=1).scalar()
        return r
